package com.cn.transfer.jobhandler;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.jiandaoyun.JdyPurchaseOrder;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.vo.PurchaseOrder;
import com.cn.transfer.common.vo.PurchaseOrderDetail;
import com.cn.transfer.handle.impl.purchase.community.PurchaseCommunity;
import com.cn.transfer.mapper.PuPurchaseOrderBMapper;
import com.cn.transfer.mapper.PuPurchaseOrderMapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 向伟典
 * @date: 2023/9/6 10:40
 * @Description: 处理已经审核的采购订单
 */
@Slf4j
@Component
public class PurchaseAddXxlJob {
    @Autowired
    private PuPurchaseOrderMapper puPurchaseOrderMapper;
    @Autowired
    private PuPurchaseOrderBMapper puPurchaseOrderBMapper;


    @Transactional
    @XxlJob("purchaseAdd")
    public void purchaseAdd(){
        String param = XxlJobHelper.getJobParam();
        List<PurchaseOrder> purchaseOrders=null;
        if (param.equals("v")){
            purchaseOrders  = puPurchaseOrderMapper.purchaseOrderNotNullDayList();
        }else {
            purchaseOrders  = puPurchaseOrderMapper.purchaseOrderNotNullList();
        }
        Header[] originalHeaders = new Header[2];
        originalHeaders[0] = new BasicHeader("Authorization", "Bearer " + KeyConstant.JDY_KEY);
        originalHeaders[1] = new BasicHeader("Content-Type", "application/json;charset=utf-8");

        List<Map<String, Object>> datas = new ArrayList<>();
        for (PurchaseOrder purchaseOrder : purchaseOrders) {
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("app_id", "64f00ef131adb70007ad6e6d");
            parameters.put("entry_id", "64f00f0e68761f0007719cf9");
            List<JdyPurchaseOrder> jdyPurchaseOrders = PurchaseCommunity.queryBased(parameters, originalHeaders, purchaseOrder.getCode(),"djbh");
            // 查询视图，这条数据是否存在
            int i1 = puPurchaseOrderMapper.inquireIsExist(purchaseOrder.getCode());
            if (i1==0){
                // 存入视图
                puPurchaseOrderMapper.insertVVPuechase(purchaseOrder);
                List<PurchaseOrderDetail> purchaseOrderDetails = purchaseOrder.getPurchaseOrderDetails();
                for (PurchaseOrderDetail purchaseOrderDetail : purchaseOrderDetails) {
                    puPurchaseOrderBMapper.insertPurchaseOrderDetail(purchaseOrderDetail);
                }
            }
            // 查询是否已经存在简道云
            if (jdyPurchaseOrders.size()>0){
                continue;
            }
            Map<String, Object> data = new HashMap<>();
            Map<String, Object> ghs = new HashMap<>();
            ghs.put("value", purchaseOrder.getPartnerName());
            data.put("ghs", ghs);

            Map<String, Object> djbh = new HashMap<>();
            djbh.put("value", purchaseOrder.getCode());
            data.put("djbh", djbh);

            Map<String, Object> yjdh = new HashMap<>();
            yjdh.put("value", purchaseOrder.getAcceptDate());
            data.put("yjdh", yjdh);

            Map<String, Object> bm = new HashMap<>();
            bm.put("value", purchaseOrder.getDepartmentName());
            data.put("bm", bm);

            Map<String, Object> ghsbm = new HashMap<>();
            ghsbm.put("value", purchaseOrder.getPartnerCode());
            data.put("ghsbm", ghsbm);

            Map<String, Object> ghsjc = new HashMap<>();
            ghsjc.put("value", purchaseOrder.getPartnerAbbName());
            data.put("ghsjc", ghsjc);

            Map<String, Object> cgy = new HashMap<>();
            cgy.put("value", purchaseOrder.getPurchaserAddress());
            data.put("cgy", cgy);

            Map<String, Object> ck = new HashMap<>();
            ck.put("value", purchaseOrder.getName());
            data.put("ck", ck);

            Map<String, Object> ddje = new HashMap<>();
            ddje.put("value", purchaseOrder.getOrigEarnestMoney());
            data.put("ddje", ddje);

            Map<String, Object> djrq = new HashMap<>();
            djrq.put("value", purchaseOrder.getVoucherdate());
            data.put("djrq", djrq);

            Map<String, Object> xsddh = new HashMap<>();
            xsddh.put("value", purchaseOrder.getSaleOrderCode());
            data.put("xsddh", xsddh);

            Map<String, Object> chdd = new HashMap<>();
            chdd.put("value", purchaseOrder.getPubuserdefnvc5());
            data.put("chdd", chdd);

            Map<String, Object> ywbm = new HashMap<>();
            ywbm.put("value", purchaseOrder.getPubuserdefnvc2());
            data.put("ywbm", ywbm);
            Map<String, Object> zdr = new HashMap<>();
            zdr.put("value", purchaseOrder.getMakerAddress());
            data.put("zdr", zdr);

            Map<String, Object> zdsj = new HashMap<>();
            zdsj.put("value", purchaseOrder.getCreateDateTime());
            data.put("zdsj", zdsj);

            Map<String, Object> shsj = new HashMap<>();
            shsj.put("value", purchaseOrder.getAuditDateTime());
            data.put("shsj", shsj);

            Map<String, Object> xsddzdr = new HashMap<>();
            xsddzdr.put("value", purchaseOrder.getSalesPersonAddress());
            data.put("xsddzdr", xsddzdr);

            Map<String, Object> xsddywy = new HashMap<>();
            xsddywy.put("value", purchaseOrder.getSalesMakerAddress());
            data.put("xsddywy", xsddywy);

            Map<String, Object> yjdhsj = new HashMap<>();
            yjdhsj.put("value", purchaseOrder.getEstimatedDateTime());
            data.put("yjdhsj", yjdhsj);

            String customerName = "";
            if (purchaseOrder.getPurchaseOrderDetails().get(0).getCustomerName() == null) {
                customerName="00";
            } else {
                customerName=purchaseOrder.getPurchaseOrderDetails().get(0).getCustomerName();
            }
            Map<String, Object> khmc = new HashMap<>();
            khmc.put("value",customerName );
            data.put("khmc", khmc);

            List<Map<String, Object>> result = new ArrayList<>();

            for (PurchaseOrderDetail detail : purchaseOrder.getPurchaseOrderDetails()) {
                Map<String, Object> detailMap = new HashMap<>();

                Map<String, Object> inventoryNameMap = new HashMap<>();
                inventoryNameMap.put("value", detail.getInventoryName());
                detailMap.put("mx_chmc", inventoryNameMap);

                Map<String, Object> productCodeMap = new HashMap<>();
                productCodeMap.put("value", detail.getProductCode());
                detailMap.put("mx_cpbm", productCodeMap);

                Map<String, Object> productNameNewMap = new HashMap<>();
                productNameNewMap.put("value", detail.getProductNameNew());
                detailMap.put("mx_cpmcx", productNameNewMap);

                Map<String, Object> specificationMap = new HashMap<>();
                specificationMap.put("value", detail.getSpecification());
                detailMap.put("mx_gzxh", specificationMap);

                Map<String, Object> specificationNewMap = new HashMap<>();
                specificationNewMap.put("value", detail.getSpecificationNew());
                detailMap.put("mx_cpggx", specificationNewMap);

                Map<String, Object> productDescriptionMap = new HashMap<>();
                productDescriptionMap.put("value", detail.getProductDescription());
                detailMap.put("mx_cpms", productDescriptionMap);

                Map<String, Object> additionalInfoNewMap = new HashMap<>();
                additionalInfoNewMap.put("value", detail.getAdditionalInfoNew());
                detailMap.put("mx_bcxxx", additionalInfoNewMap);

                Map<String, Object> additionalInfoMap = new HashMap<>();
                additionalInfoMap.put("value", detail.getAdditionalInfo());
                detailMap.put("mx_bcxx", additionalInfoMap);

                Map<String, Object> purchaserMap = new HashMap<>();
                purchaserMap.put("value", detail.getPurchaser());
                detailMap.put("mx_cgy", purchaserMap);

                Map<String, Object> quantityMap = new HashMap<>();
                quantityMap.put("value", detail.getQuantity());
                detailMap.put("mx_sl", quantityMap);

                Map<String, Object> unitNameMap = new HashMap<>();
                unitNameMap.put("value", detail.getUnitName());
                detailMap.put("mx_dj", unitNameMap);

                Map<String, Object> baseUnitPriceMap = new HashMap<>();
                baseUnitPriceMap.put("value", detail.getBaseUnitPrice());
                detailMap.put("mx_bbdj", baseUnitPriceMap);

                Map<String, Object> taxUnitPriceMap = new HashMap<>();
                taxUnitPriceMap.put("value", detail.getTaxUnitPrice());
                detailMap.put("mx_hsdj", taxUnitPriceMap);

                Map<String, Object> taxRateMap = new HashMap<>();
                taxRateMap.put("value", detail.getTaxRate());
                detailMap.put("mx_slv", taxRateMap);

                Map<String, Object> baseTaxAmountMap = new HashMap<>();
                baseTaxAmountMap.put("value", detail.getBaseTaxAmount());
                detailMap.put("mx_bbhsje", baseTaxAmountMap);

                Map<String, Object> taxAmountMap = new HashMap<>();
                taxAmountMap.put("value", detail.getTaxAmount());
                detailMap.put("mx_hsje", taxAmountMap);

                Map<String, Object> supplierCodeMap = new HashMap<>();
                supplierCodeMap.put("value", detail.getSupplierCode());
                detailMap.put("mx_gfbm", supplierCodeMap);


                Map<String, Object> customsProductNameMap = new HashMap<>();
                customsProductNameMap.put("value", detail.getCustomsProductName());
                detailMap.put("mx_bgpm", customsProductNameMap);

                Map<String, Object> productRequirementsMap = new HashMap<>();
                productRequirementsMap.put("value", detail.getProductRequirements());
                detailMap.put("mx_cpyq", productRequirementsMap);

                Map<String, Object> packagingRequirementsMap = new HashMap<>();
                packagingRequirementsMap.put("value", detail.getPackagingRequirements());
                detailMap.put("mx_bzyq", packagingRequirementsMap);

                Map<String, Object> isGiftMap = new HashMap<>();
                isGiftMap.put("value", detail.getIsGift());
                detailMap.put("mx_zp", isGiftMap);

                Map<String, Object> isLineTerminatedMap = new HashMap<>();
                isLineTerminatedMap.put("value", detail.getIsLineTerminated());
                detailMap.put("mx_zzh", isLineTerminatedMap);

                Map<String, Object> salesRepresentativeMap = new HashMap<>();
                salesRepresentativeMap.put("value", detail.getSalesRepresentative());
                detailMap.put("mx_xsywy", salesRepresentativeMap);

                Map<String, Object> productRequirementsNewMap = new HashMap<>();
                productRequirementsNewMap.put("value", detail.getProductRequirementsNew());
                detailMap.put("mx_cpmsx", productRequirementsNewMap);

                Map<String, Object> customerNameMap = new HashMap<>();
                customerNameMap.put("value", detail.getCustomerName());
                detailMap.put("mx_khmc", customerNameMap);

                Map<String, Object> salesOrderCodeMap = new HashMap<>();
                salesOrderCodeMap.put("value", detail.getSalesOrderCode());
                detailMap.put("mx_xsddh", salesOrderCodeMap);

                Map<String, Object> purchaseOrderCode = new HashMap<>();
                purchaseOrderCode.put("value", detail.getPurchaseOrderCode());
                detailMap.put("mx_cgddh", purchaseOrderCode);

                Map<String, Object> id = new HashMap<>();
                id.put("value", detail.getId());
                detailMap.put("mx_id", id);

                result.add(detailMap);
            }
            Map<String, Object> mx = new HashMap<>();
            mx.put("value", result);
            data.put("mx", mx);
            datas.add(data);


        }
        final int batchSize = 50;  // 每批处理的数据量
        int dataSize = datas.size();
        int numberOfBatches = dataSize % batchSize == 0 ? dataSize / batchSize : dataSize / batchSize + 1;

        for (int batchIndex = 0; batchIndex < numberOfBatches; batchIndex++) {
            int startIndex = batchIndex * batchSize;
            int endIndex = Math.min(startIndex + batchSize, dataSize);

            List<Map<String, Object>> lista = datas.subList(startIndex, endIndex);

            Map<String, Object> parameter = new HashMap<>();
            parameter.put("app_id", "64f00ef131adb70007ad6e6d");
            parameter.put("entry_id", "64f00f0e68761f0007719cf9");
            parameter.put("data_list", lista);

            String jsonSale = JSONUtil.toJsonStr(parameter);

            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/batch_create", originalHeaders, jsonSale);
        }

    }
}
